//
//  JsonView.m
//  BandApp
//
//  Created by Alec Flett on 8/13/09.
//  Copyright 2009 __MyCompanyName__. All rights reserved.
//

#import "FreebaseTable.h"
#import "FBTableViewCell.h"
#import "JSON/JSON.h"

@implementation FreebaseTable

@synthesize titleKey = _titleKey;
@synthesize subtitleKey = _subtitleKey;
@synthesize sortKey = _sortKey;


// The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    if ((self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil])) {
        _collection = [[FreebaseCollection alloc] initWithDelegate:self];
        _sectionRows = [[NSMutableArray alloc] init];
        _sectionTitles = [[NSMutableArray alloc] init];
        _totalRows = 0;
    }
    return self;
}


// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
    self.tableView.rowHeight = 44;
    if (!self.titleKey)
        self.titleKey = @"name";
    if (!self.sortKey)
        self.sortKey = self.titleKey;
}

/*
 // Override to allow orientations other than the default portrait orientation.
 - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
 // Return YES for supported orientations
 return (interfaceOrientation == UIInterfaceOrientationPortrait);
 }
 */

- (void)didReceiveMemoryWarning {
	// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
	
	// Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
	// Release any retained subviews of the main view.
	// e.g. self.myOutlet = nil;
}

- (void)resetSections {
    [_sectionRows removeAllObjects];
    [_sectionTitles removeAllObjects];
}

- (void)reload {
    [self.tableView reloadData];
}

- (void)dealloc {
    [super dealloc];
    [_collection release];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
#pragma unused(tableView)

    // we haven't loaded anything yet
    if ([_sectionRows count] == 0)
        return 1;
    
    // the section is past the number of sections we know about, or is the last row
    if (section >= (NSInteger)[_sectionRows count]-1)
        return _totalRows - [[_sectionRows lastObject] integerValue];

    return [[_sectionRows objectAtIndex:section+1] integerValue] -
    [[_sectionRows objectAtIndex:section] integerValue];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
#pragma unused(tableView)

    if (![_sectionRows count]) {
        return 1;
    }
    return [_sectionRows count];
}

- (NSString *)stringForItemText:(id) data {
    if (data == nil || [data isKindOfClass:[NSString class]])
        return data;
    
    // if the result is an array, just make a comma-separated array
    if ([data isKindOfClass:[NSArray class]])
        return [(NSArray*)data componentsJoinedByString:@", "];
    
    return nil;
}

- (NSString *)titleForItem:(NSDictionary*)data {
    return [self stringForItemText:[data objectForKey:self.titleKey]];
}

- (NSString *)subtitleForItem:(NSDictionary*)data {
    if (self.subtitleKey)
        return [self stringForItemText:[data objectForKey:self.subtitleKey]];
    return nil;
}

- (NSString *)sectionTitleForItem:(NSDictionary*)data {
    NSString* key = self.sortKey;
    // ignore reverse sorts
    if ([self.sortKey hasPrefix:@"-"])
        key = [self.sortKey substringFromIndex:1];
    
    NSString* title = [data valueForKeyPath:key];
    
    if (title == (NSString*)[NSNull null])
        return nil;

    // sometimes we get lists back - join 'em up
    if (0 && [title isKindOfClass:[NSArray class]]) {
        NSArray *titleList = (NSArray *)title;
        
        title = [titleList componentsJoinedByString:@", "];
        
    }
    
    // complex paths
    if ([key rangeOfString:@"."].location == NSNotFound &&
        [title isKindOfClass:[NSString class]]) {
        NSString *firstWord = [[title componentsSeparatedByString:@" "]
                               objectAtIndex:0];
        
        // try to parse out a number
        float firstNumber = [firstWord floatValue];
        if (firstNumber)
            return @"0...";
        
        // otherwise just return the first letter
        return [[firstWord substringToIndex:1] uppercaseString];
    }
    return title;
}

- (id)itemAtIndexPath:(NSIndexPath*)indexPath
{
    if (![_sectionRows count])
        return nil;
    NSInteger realIndex = [[_sectionRows objectAtIndex:indexPath.section] integerValue]
    + indexPath.row; 
    
    return [_collection itemAtIndex:realIndex];
}

- (id)imageIdForObject:(NSDictionary*)item
{
    return item;
}

//
/*
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 44;
}
*/


- (UITableViewCell *)tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    FBTableViewCell *cell = (FBTableViewCell*)[table dequeueReusableCellWithIdentifier:@"FreebaseListItem"];
    
    if (cell == nil) {
        cell = [[[FBTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"FreebaseListItem"] autorelease];
        cell.session = _collection.fbs;
    }
    
    cell.imageView.image = [UIImage imageNamed:@"no-fb-image-table.png"];
    
    if (cell.fbr) {
        [cell.fbr cancel];
        cell.fbr = nil;
    }
        
        
    NSDictionary *item = [self itemAtIndexPath:indexPath];
    if (item) {        
        cell.textLabel.text = [self titleForItem:item];
        cell.detailTextLabel.text = [self subtitleForItem:item];            
        // stupid, this is just to keep the text from shifting since the empty image is 30x30
        //NSInteger rowHeight = 44; // table.rowHeight;
        
        NSObject *imageObj = [self imageIdForObject:item];
        
        cell.imageData = imageObj;
    } else {
        cell.textLabel.text = @"Loading...";
        cell.detailTextLabel.text = nil;
        cell.imageView.image = nil;
    }
    
    return cell;
}

- (void)itemTotalLoaded:(NSInteger)total 
{
    NSLog(@"%@: loaded %d items", self, total);
    _totalRows = total;
    [self.tableView reloadData];
}

//- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
//{
//    return _sectionTitles;
//}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
#pragma unused(tableView)

    assert(section >= 0);
    if ((NSUInteger)section >= [_sectionTitles count])
        return nil;
    return [_sectionTitles objectAtIndex:section];
}

- (void)pageLoaded:(NSInteger)page data:(NSArray*)data
{
    
    if (page == 0 && [data count] < 20) {
        [_sectionRows addObject:[NSNumber numberWithInt:0]];
        [self.tableView reloadData];

        return;
    }
    
    NSUInteger currentSection = 0;
    // imagine we're on page 3 with pageSize=100, 
    // this page starts with row 300
    NSInteger pageRowStart = [_collection pageStart:page];
    
    for (NSNumber* sectionRow in _sectionRows) {
        if ([sectionRow integerValue] > pageRowStart) {
            break;
        }
                    
        // we might roll off the end here, but we'll catch it later.
        currentSection++;
    }
    
    // if we go past the current section, then we're just in the current section
    // that said, we might not have ANY sections, in which case currentSection is 0
    if (currentSection == [_sectionRows count] && !currentSection == 0)
        currentSection--;    
    
    // now imagine that we're in section 8. 
    // currentSection is now 8, so we want to remove all items 
    // from 9 to the end
    NSInteger removeCount = [_sectionRows count] - (currentSection + 1);
    if (removeCount > 0) {
        [_sectionRows removeObjectsAtIndexes:
         [NSIndexSet indexSetWithIndexesInRange:
          NSMakeRange(currentSection+1, removeCount)]];
        [_sectionTitles removeObjectsAtIndexes:
         [NSIndexSet indexSetWithIndexesInRange:
          NSMakeRange(currentSection+1, removeCount)]];        
    } else {
        // NSLog(@"Errr... wanted to remove %d (%d) rows from %d rows",
        //      currentSection+1, removeCount, [_sectionRows count]);
    }
    
     NSString *currentSectionTitle = nil;
    if ([_sectionTitles count] >0 ) {
        currentSectionTitle = [_sectionTitles objectAtIndex:currentSection];
    }
    
    NSUInteger currentRow = pageRowStart;
    for (NSDictionary *item in data) {
        NSString *itemSectionTitle = [self sectionTitleForItem:item];
        
        if (!itemSectionTitle || (NSNull*)itemSectionTitle == [NSNull null])
            itemSectionTitle = @"";
        
        if (!currentSectionTitle ||    // first time throught the loop
            ![itemSectionTitle isEqualToString:currentSectionTitle]) {
            [_sectionRows addObject:[NSNumber numberWithInt:currentRow]];
            [_sectionTitles addObject:itemSectionTitle];
            
            currentSectionTitle = itemSectionTitle;
        }
        currentRow++;
    }
    
    [self.tableView reloadData];
}



@end
